<template>
    <div class="places-box">
      <p class="places-box-items">
        <el-tag v-for="(item, index) in placeTags" :key="item.pno" closable 
        :disable-transitions="false" @close="handleClose(index)">
          {{ item.pname }}
        </el-tag>
        <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20"
          size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">
          + New Tag
        </el-button>
      </p>
      
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { ElInput, ElMessage } from 'element-plus'
import { getPlaceslist, save, del } from '@/api/places'

const placeTags = ref([]) // 列表数据
const inputVisible = ref(false) // input是否显示
const inputValue = ref('')  // input值
const InputRef = ref()  // input组件

onMounted(() => {
  loadData()
})

/// 加载数据
const loadData = () => {
  getPlaceslist().then(res => {
    if ( res.code == 200 ) {
      placeTags.value = res.data
    } else {
      ElMessage.error('数据加载失败。')
    }
  })
}

/// 删除数据
const handleClose = (index) => {
  del({pno: placeTags.value[index].pno}).then(res => {
    if ( res.code == 200 ) {
      ElMessage({
          message: '删除成功.',
          type: 'success',
      })
      placeTags.value.splice(index, 1) // dynamicTags.value.indexOf(tag)
    } else {
      ElMessage.error(res.data?res.data:'删除失败')
    }
  })
  
  
}

/// 新增
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

/// 回车提交数据
const handleInputConfirm = () => {
  if (inputValue.value) {
    const inputVal = inputValue.value
    save({pname: inputVal}).then(res => {
      if(res.code == 200) {
        placeTags.value.push({"pno": res.data, "pname": inputVal})
        ElMessage({
          message: '添加成功.',
          type: 'success',
        })
      } else {
        ElMessage.error('添加失败')
      }
    })
    console.log(placeTags.value)
    //dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<style lang="scss" scoped>
.places-box {
    min-height: 350px;
    // background-color: red;
    // padding: 20px;
    // width: 100%;
    // height: 150px;
    margin: 0px 5px;
    padding: 8px;
    box-shadow: var(--el-box-shadow-light);
    .places-box-items {
      .el-tag {
        margin: 2px 5px;
      }
      .w-20 {
        width: 10rem;
      }
    }
}

</style>